package cn.csc.framework.jzb.core;

import cn.csc.framework.jzb.config.JzbProperties;
import cn.csc.framework.jzb.vo.JzbResponse;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pingan.openbank.api.sdk.client.ApiClient;
import com.pingan.openbank.api.sdk.common.http.HttpResult;
import com.pingan.openbank.api.sdk.entity.SdkRequest;
import com.pingan.openbank.api.sdk.exception.OpenBankSdkException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 见证宝API接口客户端
 * @author liuchuang
 * @version 1.0
 * @date 2023/4/26 14:40
 * @modify
 */
@Slf4j
@Getter
public class JzbClient {

    private static final String dateFormat = "yyyyMMddHHmmss";

    private JzbProperties jzbProperties;

    private ApiClient apiClient;

    public JzbClient(ApiClient apiClient, JzbProperties jzbProperties) {
        this.apiClient = apiClient;
        this.jzbProperties = jzbProperties;
    }


    /**
     * 发送见证宝请求
     * @param jsonObject 见证宝参数
     * @param txnCode 交易码
     * @param serviceId 见证宝接口Id
     * @return
     * @throws OpenBankSdkException
     */
    public JzbResponse send(JSONObject jsonObject, String txnCode, String serviceId) throws OpenBankSdkException {
        return send(jsonObject, txnCode, serviceId, null);
    }


    /**
     * 发送见证宝请求，交易流水号由外部传入。
     * KFEJZB6110(查询银行单笔交易状态)查询所需的TranNetSeqNo(交易网流水号)即为CnsmrSeqNo
     * @param jsonObject 见证宝参数
     * @param txnCode 交易码
     * @param serviceId 见证宝接口Id
     * @param seq 交易流水号(建议规范：用户短号（6位）+日期（6位）+随机编号（10位）)。提现，充值或会员交易请求时需要外部传入
     * @return
     * @throws OpenBankSdkException
     */
    public JzbResponse send(JSONObject jsonObject, String txnCode, String serviceId, String seq) throws OpenBankSdkException {
        jsonObject.put("MrchCode", jzbProperties.getMrchCode());
        //商户号:交易客户号，Ecif客户号（例：680000376596）
        jsonObject.put("TxnClientNo", jzbProperties.getTxnClientNo());

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        if (!StringUtils.hasLength(seq)){
            seq = getCnsmrSeqNo();
        }

        //交易流水号:系统流水号，建议规范：用户短号（6位）+日期（6位）+随机编号（10位）例：C256341801183669951236平台也可自行定义，满足长度即可
        jsonObject.put("CnsmrSeqNo", seq);
        //交易码
        jsonObject.put("TxnCode", txnCode);
        //发送时间:格式为YYYYMMDDHHmmSSNNN后三位固定000
        jsonObject.put("TxnTime", LocalDateTime.now().format(formatter));

        //监管账户 15000101232520 华南城：15000101482476
        jsonObject.put("FundSummaryAcctNo", jzbProperties.getFundSummaryAcctNo());
        log.info("请求参数{}",jsonObject.toString());
        SdkRequest sdkRequest = new SdkRequest();
        sdkRequest.setInterfaceName(serviceId);
        sdkRequest.setBody(jsonObject);

        HttpResult httpResult = apiClient.invoke(sdkRequest);

        JSONObject parse = JSON.parseObject(httpResult.getData());
        JzbResponse response = new JzbResponse();
        response.setData(parse);
        if (parse.containsKey("Errors")){
            response.setSuccess(false);
        }else {
            response.setSuccess(true);
        }
        return response;
    }

    /**
     * 获取22位纯数字流水号
     * @return
     */
    public static String getSeq(){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        Random random = new Random();
        return LocalDateTime.now().format(formatter) + "" + random.nextInt(99999);
    }

    /**
     * 获取22位纯数字交易流水号
     * @return
     */
    public String getCnsmrSeqNo(){
        long workId = Math.abs(jzbProperties.getIp().hashCode()%31);
        log.info("workId : {}", workId);
        Snowflake snowflake = IdUtil.getSnowflake(workId);
        return snowflake.nextIdStr() + RandomUtil.randomNumbers(3);
    }

}
